import React, { Component } from 'react'
import { connect } from 'dva';

import { Table, Drawer, Modal, Spin } from 'antd';

import Form from './TodoSearchForm';
import Count from './Count';

import Ellipsis from '@/components/Ellipsis';

import { dealElement } from '@/utils/util';
import { ColumnProps } from 'antd/es/table';
import { UmiComponentProps, BaseComponentProps } from '@/common/type';
import ModalForm from './ModalForm'
import moment from 'moment';
import downlink from 'downloadjs'


interface IDetails {
  id: string;
  name: string;
  areaName: String;
  locationName: String;
  address: String;
  fireName: String;
  kindName: String;
  stateName: String;
  pushTime: String;
  handleName: String;
  modeName: String;
  userName: String;
  createTime: String;
  floorName: String;
  buildName: String;
  valueMap: {};
  installationAddr: String;
  images: Array<string>;
}

export interface P {
  list?: {
    data: Array<any>,
    dataCnt: number
  },
  details?: IDetails;
  historyDetails?: any;
  fileUrl?: {
    url: string,
    count: number
  },
  loadingFile: boolean
}

interface State {
  current: number;
  showInfo: boolean;
  showCount: boolean;
  showCountInfo: boolean;
  deviceId: string;
  visible: boolean;
  visibleDownload: boolean;
  total: {
    count: number,
    second: any
  }
}

type Props = P & UmiComponentProps & BaseComponentProps;

@connect(({ device_alarm, loading, menu }) => ({
  list: device_alarm.todoList || {},
  dict: device_alarm.dict,
  details: device_alarm.details || {},
  countList: device_alarm.countList || {},
  cond: device_alarm.todoCond || {},
  buttons: menu.buttons,
  fileUrl: device_alarm.fileUrl || {},
  loading: loading.effects['device_alarm/queryTodoPage'],
  loadingFile: loading.effects['device_alarm/exportFile'],
}))
class Index extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.initCurrent = this.initCurrent.bind(this);
  }

  formRef: any;

  readonly state: State = {
    current: 1,
    showInfo: false,
    showCount: false,
    showCountInfo: false,
    deviceId: null,
    visible: false,
    visibleDownload: false,
    total: {
      count: 0,
      second: 0
    }
  };

  saveFormRef = formRef => {
    this.formRef = formRef;
  };

  componentDidMount() {
    this.queryData()
  }

  private queryData(offset = 1) {
    const { dispatch } = this.props;
    dispatch({
      type: 'device_alarm/queryTodoPage',
      payload: dealElement({
        pageNum: offset,
      }),
    });
  }

  initCurrent() {
    this.setState({
      current: 1
    })
  }

  handleDownload = () => {
    const { fileUrl } = this.props
    downlink(fileUrl.url)
    this.setState({
      visibleDownload: false
    })
  }

  handleDownloadCancel = () => {
    this.setState({
      visibleDownload: false
    })
  }

  handleShow = () => {
    this.setState({
      visible: true
    })
  }

  handleCancel = () => {
    this.setState({
      visible: false
    })
  }
  handleOk = () => {
    const { dispatch } = this.props
    const { form } = this.formRef.props
    form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          visible: false,
          visibleDownload: true,
        })
        dispatch({
          type: 'device_alarm/exportFile', payload: {
            ...values,
            startTime: Array.isArray(values.createTime) && values.createTime[0] ? moment(values.createTime[0]).format("YYYY-MM-DD") : void 0,
            endTime: Array.isArray(values.createTime) && values.createTime[1] ? moment(values.createTime[1]).format("YYYY-MM-DD") : void 0,
            createTime: void 0,
          }
        }).then(() => {

          const { fileUrl } = this.props
          let url = fileUrl.url; //文件下载链接
          let fileSize = 0; //下载文件大小    
          let xhr = new XMLHttpRequest();
          xhr.open('HEAD', url, true);    // 也可用POST方式
          xhr.onreadystatechange = () => {
            if (xhr.readyState == 4) {
              if (xhr.status == 200) {
                fileSize = +(xhr.getResponseHeader('Content-Length'));
                const kb = navigator.connection.downlink * 1024 / 8;   //单位为KB/sec
                const second = (fileSize / 1024) / kb || 0
                this.setState({
                  // isLoading: false,
                  total: {
                    count: fileUrl.count,
                    second: Number.parseFloat(String(second)).toFixed(2)
                  }
                })

              } else {
                console.log('err');
              }
            }
          };
          xhr.send()

        })
      }
    })
  }

  private onShowSizeChange = (current, pageSize) => {
    const { dispatch, cond } = this.props;
    cond.pageSize = pageSize;
    dispatch({ type: `device_alarm/updateTodoCond`, payload: cond })
  }

  private handleCountClose = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'device_alarm/initCount' }).then(() => {
      this.setState({ showCount: false })
    })
  }

  private handleCount = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'device_alarm/updateCountCond',
      payload: {
        deviceId: record.id,
        beginTime: record.pushTime,
        endTime: record.lastTime,
        state: record.state
      }
    }).then(() => {
      this.setState({ showCount: true, deviceId: record.id })
    })
  }

  render() {
    const { buttons, loadingFile } = this.props;
    const btnList = {};
    if (Array.isArray(buttons)) {
      buttons.forEach(item => {
        btnList[item.name] = item.name
      });
    }
    const { data = [], dataCnt } = this.props.list;

    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      current: this.state.current,
      onChange: (current) => {
        this.setState({ current }, () => this.queryData(current));
      },
    };
    const columns: ColumnProps<IDetails>[] = [{
      title: '序号',
      dataIndex: 'ind',
      width: '75px',
      render: (text) => <>{text < 10 ? `0${text}` : text}</>
    }, {
      title: '设备名称',
      dataIndex: 'name',
      width: '120px',
      render: (text, record) => (
        <Ellipsis tooltip={true} lines={1}>
          {text}
        </Ellipsis>
      )
    }, {
      title: '安装地址',
      dataIndex: 'areaName',
      width: '250px',
      render: (text, record) => (
        <Ellipsis tooltip={true} lines={1}>
          {record.buildName || ''}{record.floorName || ''}{record.areaName || ''}{record.locationName || ''}{record.installationAddr || ''}
        </Ellipsis>
      )
    }, {
      title: '设备类型',
      dataIndex: 'kindName',
      width: '180px'
    }, {
      title: '通讯地址',
      dataIndex: 'networkAddr',
      width: '180px',
      render: (text) => (
        <Ellipsis tooltip={true} lines={1}>
          {text}
        </Ellipsis>
      )
    }, {
      title: '报警类型',
      dataIndex: 'typeName',
      width: '160px',
      render: (text, record) => (<>{text || ''}-{record.stateName || ''}</>)
    }, {
      title: '报警时间',
      dataIndex: 'pushTime',
      width: '195px'
    }, {
      title: '最新通知时间',
      dataIndex: 'lastTime',
      width: '195px'
    }, {
      title: '通知次数',
      dataIndex: 'count',
      width: '100px',
      render: (text, record) => (
        <a onClick={() => this.handleCount(record)}>{text}</a>
      )
    }, {
      title: '备注',
      dataIndex: 'remark',
      width: 'remark',
      render: (text) => (
        <Ellipsis tooltip={true} lines={2}>
          {text}
        </Ellipsis>
      )
    }];

    const ans = Array.isArray(data) ? data.map((v, index) => ({
      key: index,
      ind: index + 1,
      ...v,
      remark: v.valueMap && Array.isArray(v.valueRuleList)
        ? (Object.keys(v.valueMap))
          .map(u => {
            const rule = v.valueRuleList.find(w => w.key === u.replace(/[0-9]/g, ''));
            const ans = rule ? (rule.key === 'temperature'
              ? (rule && (!!rule.alarmUpperValue) ? `（温度正常值：<= ${rule ? rule.alarmUpperValue : '' || ''}）${v.valueMap[u]}` : '')
              : rule.key === 'leakage' ? (rule && (!!rule.maxValue) ? `（剩余电流正常值：<= ${rule ? rule.maxValue : '' || ''}）${v.valueMap[u]}` : '') :
                rule && rule.maxValue ? `（${MAP[u.replace(/[0-9]/g, '')]}正常值：${rule ? rule.minValue : '' || ''}  - ${rule ? rule.maxValue : '' || ''}）${v.valueMap[u]}` : '') : ''
            return ans;
          }).join(' ')
        : ''
    })) : []

    return (
      <>
        <Form handleShow={this.handleShow} current={this.state.current} initCurrent={this.initCurrent} new={!!btnList['新增']} />
        <Table
          columns={columns}
          pagination={pagination}
          dataSource={ans}
          loading={this.props.loading}
          bordered
        />
        <Drawer
          title="通知次数"
          placement="right"
          closable={true}
          width={700}
          onClose={this.handleCountClose}
          visible={this.state.showCount}
          destroyOnClose={true}
        >
          <Count id={this.state.deviceId} />
        </Drawer>
        <ModalForm
          isShow={false}
          wrappedComponentRef={this.saveFormRef}
          visible={this.state.visible}
          handleOk={this.handleOk}
          handleCancel={this.handleCancel}
          title='导出pdf'
        />
        <Modal
          width='35%'
          title=""
          visible={this.state.visibleDownload}
          onOk={this.handleDownload}
          onCancel={this.handleDownloadCancel}
          okText="确定下载"
        >
          <div
            style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              flexDirection: 'column',
              fontSize: 15,
              height: 180
            }}
          >
            {
              loadingFile &&
              <>
                <Spin />
                <p style={{ marginTop: 20 }}>正在统计中....</p>
              </>
            }
            {
              !loadingFile &&
              <p>共{this.state.total.count}条记录，下载大约需要{this.state.total.second}秒</p>
            }
          </div>
        </Modal>
      </>
    );
  }
}

export default Index;

const MAP = {
  'temperature': '温度',
  'voltage': '电压',
  'leakage': '剩余电流',
  'height': '水位',
  'pressure': '水压',
}